
package com.zhu.salesmanagement;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zhu.location.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.Log;
import com.zhu.salesmanagement.common.MyLocation;
import com.zhu.salesmanagement.common.MyLocation.LocationResult;
import com.zhu.salesmanagement.models.AddedStoreItemInfo;
import com.zhu.salesmanagement.models.RemindItemInfo;
import com.zhu.salesmanagement.network.ParseData;
import com.zhu.salesmanagement.network.PostData;
import com.zhu.salesmanagement.network.PostMethod;
import com.zhu.salesmanagement.network.XMLRPCMethodCallback;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.DialogUtil;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.SyncView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class AddStoreActivity extends Activity implements View.OnClickListener {

	public static final String DATAID = "dbid";
	private final static String SPLIT_TYPE = "&";
    private MyLocation mMyLocation = null;
    private Location mCurLocation = null;
    private Uri mImageCaptureUri = null;
    private final static int INVALID_VALUE = -100;
    private static final int PICK_FROM_CAMERA = 0;
    private static final int CROP_FROM_CAMERA = 1;
    private Bitmap mPhoto = null;
    private boolean mPhotoChanged = false;
    private TextView mTypeButton = null;
    private int mCurType = -1;
    private String[] mTypeArray = null;
    private boolean isNeedShowSave = false;
    private EditText mContact = null;
    private EditText mMobile = null;
    private EditText mAddress = null;
    private EditText mName = null;
    private long mDBId = INVALID_VALUE;
    private boolean isAddNewStore = true;
    private AddedStoreItemInfo mAddedStoreItemInfo = null;
    private ImageView mPhotoPreview = null;
    private String[] mTypeValue = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Parcelable parcelable = getIntent().getParcelableExtra("info");
        mAddedStoreItemInfo = (AddedStoreItemInfo) parcelable;
        mTypeValue = getResources().getStringArray(R.array.store_type_value);
        if(mAddedStoreItemInfo != null){
        	mDBId = mAddedStoreItemInfo.id;
        }

        if(mDBId != INVALID_VALUE){
        	isAddNewStore =false;
        }else{
        	isAddNewStore = true;
        }

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_addstore);

        setupView();
        initData();
    }

    private void setupView() {
        findViewById(R.id.addstore_back).setOnClickListener(this);
        findViewById(R.id.addstore_bottom_back).setOnClickListener(this);
        //findViewById(R.id.addstore_commmit).setOnClickListener(this);
        if(mDBId != INVALID_VALUE){
            findViewById(R.id.addstore_takephoto).setVisibility(View.GONE);
        }else{
            findViewById(R.id.addstore_takephoto).setOnClickListener(this);
        }

        mTypeButton = (TextView) findViewById(R.id.addstore_type);
        mTypeButton.setOnClickListener(this);
        mContact = (EditText)findViewById(R.id.addstore_contact);
        mMobile = (EditText)findViewById(R.id.addstore_mobile);
        mAddress = (EditText)findViewById(R.id.addstore_address);
        mName = (EditText)findViewById(R.id.addstore_name);
        mPhotoPreview = (ImageView)findViewById(R.id.addstore_photopreview);
    }

    private void initData() {
        if (mMyLocation == null && isAddNewStore) {
            mMyLocation = new MyLocation(AddStoreActivity.this, false, false);
            mMyLocation.getLocation(locationResult);
        }

        if(mTypeArray == null){
            mTypeArray = getResources().getStringArray(R.array.store_type);
        }
        if(mAddedStoreItemInfo != null){
            mContact.setText(mAddedStoreItemInfo.mContact);
            mMobile.setText(mAddedStoreItemInfo.mMobile);
            mAddress.setText(mAddedStoreItemInfo.mAddress);
            mName.setText(mAddedStoreItemInfo.mName);
            ((TextView) findViewById(R.id.addstore_title)).setText(mAddedStoreItemInfo.mName);
            parseType();
        }
        if(mPhoto == null){
            setBitmapFromCursor();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        if (mMyLocation != null) {
            mMyLocation.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.addstore_back:
                    finish();
                    break;
                case R.id.addstore_bottom_back:
                //case R.id.addstore_commmit:
                    saveData();
                    break;
                case R.id.addstore_takephoto:
                    takePhoto();
                    break;
                case R.id.addstore_type:
                    popSelectTypeDialog();
                    break;
            }
        }
    }

    public LocationResult locationResult = new LocationResult() {

        public void gotLocation(final Location location) {
            // Got the location!
            if (location != null) {
                mCurLocation = location;
                
            }
                
            if(isNeedShowSave){
                if(location == null){
                    Actions.toastShort(AddStoreActivity.this, getString(R.string.getlocationfailsave));
                }else{
                    Actions.toastShort(AddStoreActivity.this, getString(R.string.getlocationsuccesssave));
                }
                isNeedShowSave = false;
            }
        }
    };

    private void takePhoto() {
    	if(!isAddNewStore){
    		Actions.toastShort(this, this.getString(R.string.cannotchangephoto));
    		return;
    	}
        if (mPhoto != null) {
            popTakePhotoDialog();
        } else {
            doTakePhotoAction();
        }
    }

    private void doTakePhotoAction() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                            "tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        try {
            intent.putExtra("return-data", true);
            startActivityForResult(intent, PICK_FROM_CAMERA);
        } catch (ActivityNotFoundException e) {
            // Do nothing for now
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case CROP_FROM_CAMERA: {
                final Bundle extras = data.getExtras();
                if (extras != null) {
                    if (mPhoto != null && !mPhoto.isRecycled()) {
                        mPhoto.recycle();
                        mPhoto = null;
                    }
                    Bitmap photo = extras.getParcelable("data");
                    mPhoto = photo;
                    mPhotoChanged = true;
                    // Log.e("zhu", photo.getWidth() + " " + photo.getHeight());
                    mPhotoPreview.setImageBitmap(photo);
                    mPhotoPreview.setVisibility(View.VISIBLE);
                    saveMyBitmap("zhu", photo);
                }
                // Delete the temporary file
                File f = new File(mImageCaptureUri.getPath());
                if (f.exists()) {
                    f.delete();
                }
                break;
            }
            case PICK_FROM_CAMERA: {
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(mImageCaptureUri, "image/*");
                intent.putExtra("outputX", 300);
                intent.putExtra("outputY", 300);
                // intent.putExtra("aspectX", 1);
                // intent.putExtra("aspectY", 1);
                // intent.putExtra("scale", "true");
                // intent.putExtra("crop", "true");
                // intent.putExtra("noFaceDetection", true);
                intent.putExtra("return-data", true);
                startActivityForResult(intent, CROP_FROM_CAMERA);
                break;
            }
        }
    }

    public void saveMyBitmap(String bitName, Bitmap mBitmap) {
        File f = new File("/sdcard/" + bitName + ".jpg");
        try {
            if (f.exists()) {
                f.delete();
            }
            f.createNewFile();
        } catch (IOException e) {

        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void popTakePhotoDialog() {
        Actions.alertShowDetails(this, getString(R.string.shifoufugai),
                getString(R.string.shifoufugai_content),
                R.string.queding, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        doTakePhotoAction();
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

    private void popSelectTypeDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.select_type)
                .setItems(mTypeArray,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                mCurType = which;
                                mTypeButton.setText(mTypeArray[which]);
                            }
                        }).show();
    }

    private void saveData(){
    	if(!isAddNewStore || isGetLocationSuccess()){
    		String name = "";//mName.getText().toString().toString();
    		String address = mAddress.getText().toString().toString();
    		String mobile = "";//mMobile.getText().toString().toString();
    		String contact = mContact.getText().toString().toString();

    		if(/*name.length() < 1 ||*/ address.length() < 1 /*|| mobile.length() < 1*/ || contact.length() < 1 /*|| mCurType == -1*/ || (isAddNewStore && mPhoto == null)){
    			Actions.toastShort(this, getString(R.string.addstore_savefail));
    			return;
    		}

    		List<Object> list = new ArrayList<Object>();
    		double lat = 0,lng = 0;
    		if(mCurLocation != null){
    			lat = mCurLocation.getLatitude();
    			lng = mCurLocation.getLongitude();
          	}
    		 Map map = new HashMap<String, Object>();
             map.put("sCustomerName", name);
             map.put("sCustomerAddress", address);
             map.put("sCustomerContractor", contact);
             map.put("sTel", mobile);
             map.put("sDealtEmployeeID", Util.mVerifyUserResult.id);
             map.put("iVisitCategory", Integer.parseInt(getStoreType()));
             map.put("decLongitude", lng);
             map.put("decLatitude", lat);
             map.put("imgPhoto", flattenBitmap(mPhoto));
             list.add(map);

             putCustomerTemp(list);
             
//    		ContentValues values = new ContentValues();
//            ContentResolver cr = getContentResolver();
//            values.put(SalesSettings.MyAddStoresColumns.NAME, name);
//            values.put(SalesSettings.MyAddStoresColumns.ADDRESS, address);
//            values.put(SalesSettings.MyAddStoresColumns.MOBILE, mobile);
//            values.put(SalesSettings.MyAddStoresColumns.CONTACT, contact);
//            values.put(SalesSettings.MyAddStoresColumns.TYPE, getStoreType());

//            if(isAddNewStore){
//                if(mCurLocation == null){
//                    values.put(SalesSettings.MyAddStoresColumns.LAT, 0);
//                    values.put(SalesSettings.MyAddStoresColumns.LNG, 0);
//                }else{
//                    values.put(SalesSettings.MyAddStoresColumns.LAT, mCurLocation.getLatitude());
//                    values.put(SalesSettings.MyAddStoresColumns.LNG, mCurLocation.getLongitude());
//                }
//                values.put(SalesSettings.MyAddStoresColumns.PHOTO, flattenBitmap(mPhoto));
//            }

//            if (mDBId == INVALID_VALUE) {
//                cr.insert(SalesSettings.MyAddStoresColumns.CONTENT_URI, values);
//            } else {
//                values.put(SalesSettings.MyAddStoresColumns._ID, mDBId);
//                cr.update(SalesSettings.MyAddStoresColumns.getContentUri(mDBId, false), values, null,
//                        null);
//            }
            //Actions.toastShort(this, this.getString(R.string.save_success));
            //setResult(RESULT_OK);
            //finish();
    	}
    }

    private String getStoreType(){
        if(mCurType == -1){
            return "1";
        }
    	String type = mTypeValue[mCurType]; /*+ SPLIT_TYPE + mTypeArray[mCurType]*/;
    	return type;
    }

    private void parseType(){
    	for(int i = 0; i < mTypeValue.length; i++){
    		if(mAddedStoreItemInfo.mType.equals(mTypeValue[i])){
    			mCurType = i;
    		}
    	}
    	//mCurType = Integer.parseInt(mAddedStoreItemInfo.mType);
    	mTypeButton.setText(mTypeArray[mCurType]);
    }

    private boolean isGetLocationSuccess(){
    	if(mMyLocation != null && !mMyLocation.isGetLocationing()){
    		return true;
    	}
    	Actions.toastShort(this, getString(R.string.getlocationnotsave));
    	isNeedShowSave = true;
    	return false;
    }

    private byte[] flattenBitmap(Bitmap bitmap) {
        int size = bitmap.getWidth() * bitmap.getHeight() * 4;
        ByteArrayOutputStream out = new ByteArrayOutputStream(size);
        try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
            Log.e("Could not write icon");
            return null;
        }
    }

    private void setBitmapFromCursor(){
        if(mDBId != INVALID_VALUE){
            Cursor cursor = this.getContentResolver().query(SalesSettings.MyAddStoresColumns.getContentUri(mDBId, false), null, null, null, null);
            if(cursor != null && cursor.moveToFirst()){
                byte[] data = cursor.getBlob(cursor.getColumnIndexOrThrow(SalesSettings.MyAddStoresColumns.PHOTO));
                mPhoto = BitmapFactory.decodeByteArray(data, 0, data.length);
                if(mPhoto != null){
                    mPhotoPreview.setImageBitmap(mPhoto);
                    mPhotoPreview.setVisibility(View.VISIBLE);
                }
            }
            if(cursor != null){
            	cursor.close();
            	cursor = null;
            }
        }
    }

    private void putCustomerTemp(List<Object> list){
    	popCommitDialog();
    	Object[] object = new Object[]{ Util.mVerifyUserResult.id, Util.mVerifyUserResult.mUUID, list };
    	PostMethod.postNewAddedStores(object, new XMLRPCMethodCallback() {
			public void callFinished(int status, Object result) {
				boolean isSuccess = ParseData.parsePostData(result);
				if(isSuccess){
					mHandler.sendEmptyMessage(COMMIT_SUCCUSS);
				}else{
					mHandler.sendEmptyMessage(COMMIT_FAIL);
				}
			}
		}, SalesApplication.mApplicaton.getXMLRPCClient());
    }

    private final static int COMMIT_SUCCUSS = 1;
    private final static int COMMIT_FAIL = 2;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case COMMIT_SUCCUSS:
                	dismissCommitDialog();
                	Actions.toastShort(AddStoreActivity.this, getString(R.string.commitsuccuss));
                	popExitDialog();
                    break;
                case COMMIT_FAIL:
                	dismissCommitDialog();
                	Actions.toastShort(AddStoreActivity.this, getString(R.string.commitfail));
                    break;
            }
        }
    };

    private ProgressDialog mProgressDialog = null;

    private void popCommitDialog(){
    	if(mProgressDialog == null){
    		mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(this.getString(R.string.commiting));
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
    	}
    	mProgressDialog.show();
    }

    private void dismissCommitDialog(){
    	if(mProgressDialog != null && mProgressDialog.isShowing()){
    		mProgressDialog.cancel();
    	}
    }

    private void popExitDialog() {
        Actions.alertShowDetails(this, getString(R.string.exitclew),
                getString(R.string.exitcontent),
                R.string.queding, R.string.cancel,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {
                        finish();
                    }
                }, new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int arg1) {

                    }
                });
    }

    public static byte[] getImage(Context context){
    	byte[] mImage = null;
        if(mImage == null){
            Resources res = context.getResources();
            Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.bottom);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
            if(bmp != null){
                bmp.recycle();
            }
            mImage = baos.toByteArray();
        }
        return mImage;
    }
}
